import Taro, {FC, useEffect, useState, useDidShow, useCallback} from '@tarojs/taro'
import {View, Text, Image, Textarea, Input, Picker, ScrollView, Label} from '@tarojs/components'
import './index.scss'
import {getGlobalData} from '../../utils/global'
import loveLornUser, {MemberBasicInfoBO} from '../../api/lovelorn-user'
import {batchData} from './batch'
import {Cityoption} from './mapCity'
import env from '../../utils/env.json'
// import ScaleImg from '../../components/ScaleImg'
const MyInfo: FC = () => {
  const [userData, setUserData] = useState({} as MemberBasicInfoBO)
  const [imgArray, setImgArray] = useState([])
  const [multiArray, setMultiArray] = useState([[]])
  const [multiIndex, setMultiIndex] = useState([[]])
  const [height, setHeight] = useState([])
  const [weight, setWeight] = useState([])
  useEffect(() => {
    let temp = [[]]
    temp = [[...Cityoption], [...Cityoption[0].children]]
    setMultiArray(temp)
    let arr = []
    for (let i = 140; i < 200; i++) {
      arr.push(i + 'CM')
    }
    let weightArr = []
    for (let j = 30; j < 100; j++) {
      weightArr.push(j + 'kg')
    }
    setHeight(arr)
    setWeight(weightArr)
  }, [])
  const [userInfo, setUserInfo] = useState(getGlobalData('loginVO') ? getGlobalData('loginVO') : {})
  useEffect(() => {
    Taro.getStorage({
      key: 'loginVO',
      success: function(res) {
        console.log(res, 'aaa')
        setUserInfo(res.data)
      },
    })
  }, [])
  const getUserData = async () => {
    console.log(userInfo, 'userInfo')

    try {
      let res = await loveLornUser.memberBasicInfos.selectByUserId({
        userId: userInfo && userInfo.user && userInfo.user.userId,
      })
      setUserData(res)
    } catch (ex) {
      console.log(ex, 'ex')
    }
  }
  const getUserSelect = async () => {
    try {
      let res = await loveLornUser.batch.get('')
      console.log(res, 'res')
    } catch (ex) {
      console.log(ex)
    }
  }
  const changeEdu = e => {
    setUserData(() => {
      return {
        ...userData,
        educationBackgroundValue: batchData.sl_education_background[e.detail.value].value,
        educationBackground: batchData.sl_education_background[e.detail.value].key,
      }
    })
  }

  const changeOccupation = e => {
    setUserData(() => {
      return {
        ...userData,
        occupationValue: batchData.member_career[e.detail.value].value,
        occupation: batchData.member_career[e.detail.value].key,
      }
    })
  }

  const changeMonthly = e => {
    setUserData(() => {
      return {
        ...userData,
        monthlyProfileValue: batchData.member_monthly_income[e.detail.value].value,
        monthlyProfile: batchData.member_monthly_income[e.detail.value].key,
      }
    })
  }

  const changeEduMarital = e => {
    setUserData(() => {
      return {
        ...userData,
        maritalStatusValue: batchData.sweetheart_marital_status[e.detail.value].value,
        maritalStatus: batchData.sweetheart_marital_status[e.detail.value].key,
      }
    })
  }
  const changeChildren = e => {
    setUserData(() => {
      return {...userData, hasChildren: batchData.sl_has_children[e.detail.value].key}
    })
  }

  useEffect(() => {
    if (userInfo && userInfo.user && userInfo.user.userId) {
      getUserData()
    }
  }, [userInfo])
  const renderMonth = id => {
    let res = batchData.member_monthly_income.filter(el => {
      return el.key == id
    })
    return res[0].value
  }
  const renderMaRital = id => {
    console.log(id, 'id')
    let res = batchData.sweetheart_marital_status.filter(el => {
      return el.key == id
    })
    return res[0].value
  }

  const saveInfo = async () => {
    if (userData.userImg.includes('https://cdn')) {
      try {
        let res = await loveLornUser.memberBasicInfos.updateByUserId({...userData})
        if (res) {
          Taro.showToast({
            title: '信息保存成功',
            icon: 'none',
            success: function() {
              Taro.navigateBack({
                delta: 1,
              })
            },
          })
        } else {
          console.log(res, 'fail')
        }
      } catch (ex) {
        console.log(ex, 'ex')
        Taro.showToast({
          title: `${ex.data.msg}`,
          icon: 'none',
        })
      }
    } else {
      Taro.uploadFile({
        url: `${env.httpBaseUrl}/platform-support/v1.4/pt/uploads/action/upload-image`,
        filePath: userData.userImg,
        name: 'file',
        header: {
          tenantId: 'lovelorn',
          devType: 4,
          userId: userInfo && userInfo.user && userInfo.user.userId,
          token: userInfo && userInfo.authInfo && userInfo.authInfo.token,
        },
        success: function(res) {
          const resourceUrl = JSON.parse(res.data).data.resourceUrl
          console.log(resourceUrl)
          // try {
          loveLornUser.memberBasicInfos
            .updateByUserId({
              ...userData,
              userImg: resourceUrl,
            })
            .then(result => {
              console.log(result, 'tijiaoresly')
              if (result) {
                Taro.showToast({
                  title: '信息保存成功',
                  icon: 'none',
                  success: function() {
                    Taro.navigateBack({
                      delta: 1,
                    })
                  },
                })
              } else {
                console.log('请稍后再试')
              }
            })
            .catch(ex => {
              console.log(ex, 'ex')
              Taro.showToast({
                title: `${ex.data.msg}`,
                icon: 'none',
              })
            })

          // .then(result => {
          //   if (result) {
          //     Taro.showToast({
          //       title: '信息保存成功',
          //       icon: 'none',
          //     })
          //   }
          // })
          // } catch (ex) {
          //   console.log(ex, 'ex')
          //   Taro.showToast({
          //     title: `${ex.msg}`,
          //     icon: 'none',
          //   })
          // }
        },
        fail: function(ex) {
          console.log(ex)
          Taro.showToast({
            icon: 'none',
            title: '图片上传失败',
          })
        },
        complete(result) {
          console.log(result, 'result')
        },
      })
    }
  }
  const changeUserSignature = e => {
    setUserData(() => {
      return {...userData, userSignature: e.detail.value}
    })
  }
  const chooseImage = e => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths, 'tempFilePaths')
        setUserData(() => {
          return {...userData, userImg: tempFilePaths[0]}
        })
      },
    })
  }
  const getDateTimeStamp = (dateStr: string) => {
    if (!dateStr) {
      return 0
    }
    return Date.parse(dateStr.replace(/-/gi, '/'))
  }

  const changeDate = e => {
    console.log(e.detail.value, 'e')
    if (getDateTimeStamp(e.detail.value) > +new Date().getTime()) {
      Taro.showToast({
        title: '请选择正确的出生日期',
      })
      return
    }
    setUserData(() => {
      return {...userData, birthday: e.detail.value}
    })
  }

  const changeCity = e => {
    console.log(e.detail.value, 'e')
    console.log(Cityoption[e.detail.value[0]].children[e.detail.value[1]].label)
    setUserData(() => {
      return {
        ...userData,
        userCity: Cityoption[e.detail.value[0]].children[e.detail.value[1]].label,
        cityCode: Cityoption[e.detail.value[0]].children[e.detail.value[1]].value,
      }
    })
  }

  const changeCloumn = e => {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value)

    const data = {
      multiArray: multiArray,
      multiIndex: multiIndex,
    }
    data.multiIndex[e.detail.column] = e.detail.value
    switch (e.detail.column) {
      case 0:
        data.multiArray[1] = Cityoption[e.detail.value].children
        setMultiArray(data.multiArray)
        setMultiIndex([e.detail.value])
        // setMultiIndex(data.multiIndex)
        break
    }
  }

  const changeHeight = e => {
    setUserData(() => {
      return {...userData, heigth: height[e.detail.value].replace('CM', '')}
    })
  }
  const renderHeight = e => {
    let reg = new RegExp(/CM/)
    if (e.toString().match(reg)) {
      return e
    } else {
      return e + 'CM'
    }
  }

  const changeNickName = e => {
    setUserData(() => {
      return {...userData, nickName: e.detail.value}
    })
  }

  const changeWeight = e => {
    setUserData(() => {
      return {...userData, weight: weight[e.detail.value].replace('kg', '')}
    })
  }
  const renderWeight = e => {
    let reg = new RegExp(/kg/)
    if (e.toString().match(reg)) {
      return e
    } else {
      return e + 'kg'
    }
  }

  return (
    <View className="myInfo">
      <View className="myInfoBasic">
        <View className="basicTitle">基础信息</View>
        <View className="flex flexList flexCenter">
          <View className="basicLeft">头像</View>
          <View className="basicRight flexCenter ">
            <View className="userAvater">
              <Image
                src={userData.userImg}
                onClick={() => {
                  Taro.previewImage({
                    current: userData.userImg,
                    urls: [userData.userImg],
                  })
                  // setImgArray([userData.userImg])
                }}
                className="userAvaterImg"
              />
            </View>
            <View className="userArrow" onClick={chooseImage}>
              <Text className="iconfont iconarrow-right"></Text>
            </View>
          </View>
        </View>
        <View className="flex flexList ">
          <View className="basicLeft">昵称</View>
          <View className="basicRight ">
            <Input className="basicInput" onInput={changeNickName} value={userData.nickName} />
          </View>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">性别</View>
          <View className="basicRight ">{userData.gender == 1 ? '男士' : '女士'}</View>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">出生日期</View>
          <Picker
            className="basicRight"
            mode="date"
            headerText="选择出身日期"
            onChange={changeDate}>
            {userData.birthday ? userData.birthday : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">学历</View>
          <Picker
            className="basicRight"
            mode="selector"
            range={batchData.sl_education_background}
            onChange={changeEdu}
            rangeKey="value">
            {userData.educationBackgroundValue != null
              ? userData.educationBackgroundValue
              : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">职业</View>
          <Picker
            className="basicRight"
            mode="selector"
            range={batchData.member_career}
            onChange={changeOccupation}
            rangeKey="value">
            {userData.occupationValue != null ? userData.occupationValue : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">月收入</View>
          <Picker
            className="basicRight"
            mode="selector"
            range={batchData.member_monthly_income}
            onChange={changeMonthly}
            rangeKey="value">
            {userData.monthlyProfile != null ? renderMonth(userData.monthlyProfile) : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>

        <View className="flex flexList">
          <View className="basicLeft">所在地</View>
          <Picker
            className="basicRight"
            mode="multiSelector"
            value={multiIndex}
            range={multiArray}
            onChange={changeCity}
            onColumnChange={changeCloumn}
            rangeKey="label">
            {userData.userCity ? userData.userCity : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">身高</View>
          <Picker className="basicRight" mode="selector" range={height} onChange={changeHeight}>
            {userData.heigth != null ? renderHeight(userData.heigth) : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">体重</View>
          {/* <Text>请选择</Text> */}
          {/* renderWeight */}
          <Picker className="basicRight" mode="selector" range={weight} onChange={changeWeight}>
            {userData.weight != null ? renderWeight(userData.weight) : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">婚姻状况</View>

          <Picker
            className="basicRight"
            mode="selector"
            range={batchData.sweetheart_marital_status}
            onChange={changeEduMarital}
            rangeKey="value">
            {userData.maritalStatus && userData.maritalStatusValue != null
              ? renderMaRital(userData.maritalStatus)
              : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
        <View className="flex flexList">
          <View className="basicLeft">有请选择子女</View>
          <Picker
            className="basicRight"
            mode="selector"
            range={batchData.sl_has_children}
            onChange={changeChildren}
            rangeKey="value">
            {userData.hasChildren != null ? (userData.hasChildren == 0 ? '无' : '有') : '请选择'}
            <Text className="iconfont iconarrow-right"></Text>
          </Picker>
        </View>
      </View>
      <View className="mySignture">
        <View className="basicTitle">交友宣言</View>
        <Textarea
          onInput={changeUserSignature}
          className="basicText"
          value={userData.userSignature}
          placeholder="请输入你的交友宣言"></Textarea>
      </View>
      <View className="saveBtn" onClick={saveInfo}>
        保存
      </View>
    </View>
  )
}

export default MyInfo
